<template>
    <div class="tags-view-container">
        <el-tag v-for="(item,index) in tagViewList" :key="item.path" class="mx-1" :closable="item.path == route.path ?false:true" :type="item.path == route.path ?'success':''" @close="handleClose(index)" size="large" hit @contextmenu.prevent="openContextMenu($event,index)">
            <router-link :to="item.path">{{ item.title }}</router-link>
        </el-tag>
        <ContextMenu v-show="visible" :style="menuStyle" :index="selectIndex"></ContextMenu>
    </div>
</template>


<script setup>
// tag路由
import { userappStore } from "@/store/app.js";
import { computed, watch,ref} from 'vue'
import { useRouter,useRoute } from 'vue-router'
import ContextMenu from './ContextMenu.vue'

const AppStore = userappStore()
const router = useRouter() // 主路由
const route = useRoute() // 当前路由
const visible = ref(false) // 右键菜单的显示状态
const menuStyle = ref({})
const selectIndex = ref(0)
const tagViewList = computed(() => {
    return AppStore.tagsViewList
})

// 路由发生变化记录到大菠萝和本地
watch(router.currentRoute, () => {
    const tag = router.currentRoute.value
    // 新增标签
    AppStore.addTagsViewList({
        path: tag.path,
        title: tag.meta.title
    })
}, {
    immediate: true
})

// 删除标签
const handleClose = (index)=>{
    AppStore.removeTagsViewList(0,index)
}

// 右键菜单
const openContextMenu = (e,index)=>{
    const {x,y} = e
    menuStyle.value = {
        left:x+'px',
        top:y+'px'
    }
    selectIndex.value = index
    visible.value = !visible.value
}

const closeContextMenu = ()=>{
    visible.value = false
}

// 监听右键菜单的变化，如果打开了就给document绑定一个事件，点击就可以关闭右键菜单
watch(visible,()=>{
    if(visible.value){
        document.addEventListener('click',closeContextMenu)
    }else{
        document.removeEventListener('click',closeContextMenu)
    }
})
</script>

<style lang="scss" scoped>
.tags-view-container{
    margin-top: 20px;

}
</style>